package com.example.demo.service.impl;

import com.example.demo.dao.OrderDao;
import com.example.demo.entity.Order;
import com.example.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author liuxianchun
 * @date 2021/1/21
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void addOrder(Long orderId,int userId, int productId, int productNum, BigDecimal productPrice) {
        orderDao.addOrder(orderId,userId,productId,productNum,productPrice);
        Map<Object, Object> salesNum = redisTemplate.opsForHash().entries("sales_num");
        if(salesNum.isEmpty()||salesNum.get(productId+"")==null){
            salesNum.put(productId+"",productNum);
        }else{
            salesNum.put(productId+"",(int)salesNum.get(productId+"")+productNum);
        }
        redisTemplate.opsForHash().putAll("sales_num",salesNum);
    }

    @Override
    public void addOrderNoPay(Long orderId,int userId, int productId, int productNum, BigDecimal productPrice) {
        orderDao.addOrderNoPay(orderId,userId,productId,productNum,productPrice);
    }


    @Override
    public List<Order> getOrders(Long orderId) {
        return orderDao.getOrders(orderId);
    }

    @Override
    public List<Long> getOrderIdByUser(int user_id) {
        return orderDao.getOrderIdByUser(user_id);
    }


    @Override
    public Long getOrderId() {
        return orderDao.getOrderId();
    }

    @Override
    public int orderPay(Integer user_id, Long order_id) {
        if(null==user_id||null==order_id)
            return 0;
        List<Order> orders = orderDao.getOrders(order_id);
        Map<Object, Object> sales_num = redisTemplate.opsForHash().entries("sales_num");
        for(Order order:orders){
            int product_id = order.getProductId();
            int product_num = order.getProductNum();
            if(sales_num.isEmpty()||sales_num.get(product_id+"")==null){
                sales_num.put(product_id+"",product_num);
            }else{
                sales_num.put(product_id+"",(int)sales_num.get(product_id+"")+product_num);
            }
            redisTemplate.opsForHash().putAll("sales_num",sales_num);
        }
        return orderDao.orderPay(user_id,order_id);
    }
}
